package com.fausto.learnimprint.core.service.impl

import cn.hutool.core.lang.id.NanoId
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper
import com.baomidou.mybatisplus.extension.plugins.pagination.Page
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl
import com.fausto.learnimprint.cache.RedisCache
import com.fausto.learnimprint.cache.RedisKey
import com.fausto.learnimprint.core.mapper.CodeMapper
import com.fausto.learnimprint.core.model.entity.Code
import com.fausto.learnimprint.core.service.ICodeService
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Service
import org.springframework.transaction.annotation.Transactional

/**
 *
 *
 * 服务实现类
 *
 *
 * @author fausto
 * @since 2022-03-28
 */
@Service
class CodeServiceImpl :
    ServiceImpl<CodeMapper, Code>(),
    ICodeService {

    @Autowired
    lateinit var codeMapper: CodeMapper

    /**
     *      生成新邀请码保存到数据库后返回
     */
    @Transactional(rollbackFor = [Exception::class])
    override fun newCode(): Code {
        //通过NanoId生成新的32位邀请码
        val code = NanoId.randomNanoId(32)

        val codeEntity = Code().apply {
            this.codeId = code
            this.codeState = 0
        }
        //插入到数据库中
        codeMapper.insert(codeEntity)
        //返回邀请码实体
        return codeEntity
    }

    /**
     *      分页获取邀请码
     *          + AOP缓存处理
     */
    @RedisCache(key = RedisKey.CODE_KEY)
    override fun getCacheCode(page: Int, showCount: Int): List<Code?> {
        return codeMapper.selectPage(
            Page(page.toLong(), showCount.toLong()),
            QueryWrapper()
        ).records
    }
}